import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { Helmet, history } from '@umijs/max';
import { Alert, Tabs } from 'antd';
import Settings from '../../../../config/defaultSettings';
import React, { useRef, useState } from 'react';
import MyCaptchaInput, { CaptchaInputRef } from '@/components/MyCaptchaInput';
import { login } from '@/services/system/login';
import useUserInfo from '@/hooks/useUserInfo';
import MyIcon from '@/components/MyIcon';
import Footer from '@/components/Footer';

const styles = {
  action:
    'ml-[8px] text-black/20 text-[24px] align-middle cursor-pointer transition-[color] duration-300 hover:text-[#0958d9]',
  container:
    "flex flex-col h-[100vh] overflow-auto bg-100 bg-[url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')]",
};

const ActionIcons = () => {
  return (
    <>
      <MyIcon name="AlipayCircleOutlined" key="AlipayCircleOutlined" className={styles.action} />
      <MyIcon name="TaobaoCircleOutlined" key="TaobaoCircleOutlined" className={styles.action} />
      <MyIcon name="WeiboCircleOutlined" key="WeiboCircleOutlined" className={styles.action} />
    </>
  );
};

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<string>('');
  const [type, setType] = useState<string>('account');
  const captchaInputRef = useRef<CaptchaInputRef | null>(null);
  const { saveUserInfo } = useUserInfo();
  const handleSubmit = (values: USER_TYPE.LoginParams) => {
    // 登录
    values.grant_type = 'password';
    values.client_id = 'admin';
    values.client_secret = '123456';
    values.key = captchaInputRef.current!.getCaptchaKey();
    login(values)
      .then((ret) => {
        console.log(ret);
        if (!ret.success) {
          setUserLoginState(ret.message);
          return;
        }
        const urlParams = new URL(window.location.href).searchParams;
        setUserLoginState('');
        saveUserInfo(ret.data, () =>
          setTimeout(() => {
            // message.success('登录成功！');
            history.push(urlParams.get('redirect') || '/');
          }, 0),
        );
      })
      .catch((e) => {
        setUserLoginState(e.message);
      })
      .finally(() => {
        captchaInputRef.current?.onClickImage();
      });

    // 如果失败去设置用户错误信息
  };

  return (
    // <div className={styles.container}>
    <div className={styles.container}>
      <Helmet>
        <title>登录页 - {Settings.title}</title>
      </Helmet>
      <div className="flex-1 py-[32px]">
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/logo.svg" />}
          title="Ant Design"
          subTitle="Ant Design 是西湖区最具影响力的 Web 设计规范"
          actions={['其他登录方式', <ActionIcons key="icons" />]}
          onFinish={(values) => handleSubmit(values as USER_TYPE.LoginParams)}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'account',
                label: '账户密码登录',
              },
              {
                key: 'mobile',
                label: '手机号登录',
              },
            ]}
          />
          {userLoginState.length > 0 && <LoginMessage content={userLoginState} />}
          {type === 'account' && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <MyIcon name="UserOutlined" />,
                }}
                placeholder="用户名"
                rules={[
                  {
                    required: true,
                    message: '请输入用户名!',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                allowClear
                fieldProps={{
                  size: 'large',
                  prefix: <MyIcon name="LockOutlined" />,
                }}
                placeholder="密码"
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
              <MyCaptchaInput ref={captchaInputRef} />
            </>
          )}

          {type === 'mobile' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MyIcon name="MobileOutlined" />,
                }}
                name="mobile"
                placeholder="手机号"
                rules={[
                  {
                    required: true,
                    message: '请输入手机号！',
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: '手机号格式错误！',
                  },
                ]}
              />
              {/*<ProFormCaptcha*/}
              {/*  fieldProps={{*/}
              {/*    size: 'large',*/}
              {/*    prefix: <LockOutlined />,*/}
              {/*  }}*/}
              {/*  captchaProps={{*/}
              {/*    size: 'large',*/}
              {/*  }}*/}
              {/*  placeholder="请输入验证码"*/}
              {/*  captchaTextRender={(timing, count) => {*/}
              {/*    if (timing) {*/}
              {/*      return `${count} 获取验证码`;*/}
              {/*    }*/}
              {/*    return '获取验证码';*/}
              {/*  }}*/}
              {/*  name="captcha"*/}
              {/*  rules={[*/}
              {/*    {*/}
              {/*      required: true,*/}
              {/*      message: '请输入验证码！',*/}
              {/*    },*/}
              {/*  ]}*/}
              {/*  onGetCaptcha={async (phone) => {*/}
              {/*    const result = await getFakeCaptcha({*/}
              {/*      phone,*/}
              {/*    });*/}
              {/*    if (!result) {*/}
              {/*      return;*/}
              {/*    }*/}
              {/*    message.success('获取验证码成功！验证码为：1234');*/}
              {/*  }}*/}
              {/*/>*/}
            </>
          )}
          {/*<div*/}
          {/*  style={{*/}
          {/*    marginBottom: 24,*/}
          {/*  }}*/}
          {/*>*/}
          {/*  <ProFormCheckbox noStyle name="autoLogin">*/}
          {/*    <FormattedMessage id="pages.login.rememberMe" defaultMessage="自动登录"/>*/}
          {/*  </ProFormCheckbox>*/}
          {/*  <a*/}
          {/*    style={{*/}
          {/*      float: 'right',*/}
          {/*    }}*/}
          {/*  >*/}
          {/*    <FormattedMessage id="pages.login.forgotPassword" defaultMessage="忘记密码"/>*/}
          {/*  </a>*/}
          {/*</div>*/}
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
